<template>
  <div class="erp-inventory-report">
    <el-card shadow="never">
      <template #header>
        <div class="erp-inventory-report__header">
          <span>库存报表</span>
        </div>
      </template>
      <el-tabs v-model="activeTab" @tab-change="onTabChange">
        <el-tab-pane label="当前库存" name="balance">
          <el-form :inline="true" class="erp-inventory-report__search" @submit.prevent>
            <el-form-item label="仓库">
              <el-select v-model="query.balance.warehouseId" clearable filterable placeholder="请选择仓库" style="width: 200px">
                <el-option
                  v-for="w in warehouseOptions"
                  :key="w.warehouseId"
                  :label="w.warehouseName"
                  :value="String(w.warehouseId)"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="物料">
              <el-select v-model="query.balance.materialId" clearable filterable placeholder="请选择物料" style="width: 200px">
                <el-option
                  v-for="m in materialOptions"
                  :key="m.materialId"
                  :label="m.materialName"
                  :value="String(m.materialId)"
                />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" size="small" @click="loadBalance">查询</el-button>
              <el-button size="small" @click="resetBalance">重置</el-button>
            </el-form-item>
          </el-form>
          <el-table :data="balanceList" size="small" style="width: 100%">
            <el-table-column prop="warehouseId" label="仓库ID" min-width="120" />
            <el-table-column prop="materialId" label="物料ID" min-width="120" />
            <el-table-column prop="qtyOnHand" label="库存数量" min-width="120" />
            <el-table-column prop="movingAvgCost" label="单位成本" min-width="120">
              <template #default="{ row }">
                {{ row.movingAvgCost ? Number(row.movingAvgCost).toFixed(2) : '0.00' }}
              </template>
            </el-table-column>
            <el-table-column prop="amount" label="库存金额" min-width="120">
              <template #default="{ row }">
                {{ row.amount ? Number(row.amount).toFixed(2) : '0.00' }}
              </template>
            </el-table-column>
            <el-table-column prop="updateTime" label="更新时间" min-width="160" />
          </el-table>
          <div class="erp-inventory-report__pagination">
            <el-pagination
              background
              layout="total, sizes, prev, pager, next, jumper"
              :total="balanceTotal"
              :page-sizes="[10, 20, 50, 100]"
              :page-size="balancePageSize"
              :current-page="balancePageNum"
              @size-change="onBalanceSizeChange"
              @current-change="onBalancePageChange"
            />
          </div>
        </el-tab-pane>
        <el-tab-pane label="出入库明细" name="ledger">
          <el-form :inline="true" class="erp-inventory-report__search" @submit.prevent>
            <el-form-item label="仓库">
              <el-select v-model="query.ledger.warehouseId" clearable filterable placeholder="请选择仓库" style="width: 200px">
                <el-option
                  v-for="w in warehouseOptions"
                  :key="w.warehouseId"
                  :label="w.warehouseName"
                  :value="String(w.warehouseId)"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="物料">
              <el-select v-model="query.ledger.materialId" clearable filterable placeholder="请选择物料" style="width: 200px">
                <el-option
                  v-for="m in materialOptions"
                  :key="m.materialId"
                  :label="m.materialName"
                  :value="String(m.materialId)"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="单据类型">
              <el-select v-model="query.ledger.billType" placeholder="全部" clearable>
                <el-option value="PO_IN" label="采购入库" />
                <el-option value="SO_OUT" label="销售出库" />
              </el-select>
            </el-form-item>
            <el-form-item label="出入库类型">
              <el-select v-model="query.ledger.ioType" placeholder="全部" clearable>
                <el-option value="IN" label="入库" />
                <el-option value="OUT" label="出库" />
              </el-select>
            </el-form-item>
            <el-form-item label="业务时间">
              <el-date-picker
                v-model="query.ledger.timeRange"
                type="datetimerange"
                range-separator="至"
                start-placeholder="开始"
                end-placeholder="结束"
                value-format="YYYY-MM-DD HH:mm:ss"
              />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" size="small" @click="loadLedger">查询</el-button>
              <el-button size="small" @click="resetLedger">重置</el-button>
            </el-form-item>
          </el-form>
          <el-table :data="ledgerList" size="small" style="width: 100%">
            <el-table-column prop="warehouseId" label="仓库ID" min-width="120" />
            <el-table-column prop="materialId" label="物料ID" min-width="120" />
            <el-table-column prop="billType" label="单据类型" min-width="120" />
            <el-table-column prop="billNo" label="单据号" min-width="140" />
            <el-table-column prop="ioType" label="出入库类型" min-width="120">
              <template #default="{ row }">
                <el-tag v-if="row.ioType === 'IN'" type="success">入库</el-tag>
                <el-tag v-else-if="row.ioType === 'OUT'" type="danger">出库</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="qty" label="数量" min-width="120" />
            <el-table-column prop="unitCostAfter" label="单位成本" min-width="120">
              <template #default="{ row }">
                {{ row.unitCostAfter ? Number(row.unitCostAfter).toFixed(2) : '0.00' }}
              </template>
            </el-table-column>
            <el-table-column label="金额" min-width="120">
              <template #default="{ row }">
                {{ row.ioType === 'IN' ? (row.amountIn ? Number(row.amountIn).toFixed(2) : '0.00') : (row.amountOut ? Number(row.amountOut).toFixed(2) : '0.00') }}
              </template>
            </el-table-column>
            <el-table-column prop="bizTime" label="业务时间" min-width="160" />
          </el-table>
          <div class="erp-inventory-report__pagination">
            <el-pagination
              background
              layout="total, sizes, prev, pager, next, jumper"
              :total="ledgerTotal"
              :page-sizes="[10, 20, 50, 100]"
              :page-size="ledgerPageSize"
              :current-page="ledgerPageNum"
              @size-change="onLedgerSizeChange"
              @current-change="onLedgerPageChange"
            />
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref } from 'vue'
import { pageInventoryBalance, pageInventoryLedger } from '@/api/erp/report'
import { listWarehouse } from '@/api/erp/warehouse'
import { listMaterial } from '@/api/erp/material'
import { ElMessage } from 'element-plus'

const activeTab = ref('balance')

// 当前库存
const balanceList = ref<any[]>([])
const balanceTotal = ref(0)
const balancePageNum = ref(1)
const balancePageSize = ref(10)

// 下拉选项
const warehouseOptions = ref<any[]>([])
const materialOptions = ref<any[]>([])

const query = reactive({
  balance: {
    warehouseId: '',
    materialId: ''
  },
  ledger: {
    warehouseId: '',
    materialId: '',
    billType: '',
    ioType: '',
    timeRange: [] as string[]
  }
})

// 出入库明细
const ledgerList = ref<any[]>([])
const ledgerTotal = ref(0)
const ledgerPageNum = ref(1)
const ledgerPageSize = ref(10)

const loadWarehouseOptions = async () => {
  try {
    const res = await listWarehouse({ pageNum: 1, pageSize: 1000 })
    warehouseOptions.value = res?.data?.records || []
  } catch (error) {
    console.error('加载仓库列表失败:', error)
  }
}

const loadMaterialOptions = async () => {
  try {
    const res = await listMaterial({ pageNum: 1, pageSize: 1000 })
    materialOptions.value = res?.data?.records || []
  } catch (error) {
    console.error('加载物料列表失败:', error)
  }
}

const loadBalance = async () => {
  try {
    const res = await pageInventoryBalance({
      pageNum: balancePageNum.value,
      pageSize: balancePageSize.value,
      warehouseId: query.balance.warehouseId || undefined,
      materialId: query.balance.materialId || undefined
    })
    balanceList.value = res?.data?.records || []
    balanceTotal.value = res?.data?.total || 0
    if (balanceTotal.value === 0) {
      ElMessage.info('暂无库存数据。请先创建并过账入库单据。')
    }
  } catch (error: any) {
    console.error('加载库存数据失败:', error)
    ElMessage.error('加载库存数据失败：' + (error?.message || '未知错误'))
  }
}

const loadLedger = async () => {
  try {
    const res = await pageInventoryLedger({
      pageNum: ledgerPageNum.value,
      pageSize: ledgerPageSize.value,
      warehouseId: query.ledger.warehouseId || undefined,
      materialId: query.ledger.materialId || undefined,
      billType: query.ledger.billType || undefined,
      ioType: query.ledger.ioType || undefined,
      startTime: Array.isArray(query.ledger.timeRange) && query.ledger.timeRange.length === 2 ? query.ledger.timeRange[0] : undefined,
      endTime: Array.isArray(query.ledger.timeRange) && query.ledger.timeRange.length === 2 ? query.ledger.timeRange[1] : undefined
    })
    ledgerList.value = res?.data?.records || []
    ledgerTotal.value = res?.data?.total || 0
    if (ledgerTotal.value === 0) {
      ElMessage.info('暂无出入库明细。请先创建并过账入库/出库单据。')
    }
  } catch (error: any) {
    console.error('加载出入库明细失败:', error)
    ElMessage.error('加载出入库明细失败：' + (error?.message || '未知错误'))
  }
}

const onTabChange = (tab: string) => {
  if (tab === 'balance') {
    loadBalance()
  } else if (tab === 'ledger') {
    loadLedger()
  }
}

const resetBalance = () => {
  query.balance.warehouseId = ''
  query.balance.materialId = ''
  balancePageNum.value = 1
  loadBalance()
}

const resetLedger = () => {
  query.ledger.warehouseId = ''
  query.ledger.materialId = ''
  query.ledger.billType = ''
  query.ledger.ioType = ''
  query.ledger.timeRange = []
  ledgerPageNum.value = 1
  loadLedger()
}

const onBalancePageChange = (p: number) => {
  balancePageNum.value = p
  loadBalance()
}

const onBalanceSizeChange = (s: number) => {
  balancePageSize.value = s
  balancePageNum.value = 1
  loadBalance()
}

const onLedgerPageChange = (p: number) => {
  ledgerPageNum.value = p
  loadLedger()
}

const onLedgerSizeChange = (s: number) => {
  ledgerPageSize.value = s
  ledgerPageNum.value = 1
  loadLedger()
}

onMounted(() => {
  loadWarehouseOptions()
  loadMaterialOptions()
  loadBalance()
})
</script>

<style scoped lang="scss">
.erp-inventory-report {
  &__header {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
  &__pagination {
    margin-top: 12px;
    display: flex;
    justify-content: flex-end;
  }
}
</style>

